/*
 * 版权所有 ( c ) 联想集团有限公司 2005-2009 保留所有权利。
 * 项目：	Lenovo Push Service
 * 文件名：	CharacterEncodingFilter.java
 * 版本:    1.0
 * 描述：	
 * 作者：	刘兵召
 * 日期：	2009-7-2 
 * 修改历史：
 * 【时间】		【修改者】	【修改内容】
 */
package com.feng.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ClassUtils;

import com.lenovo.lps.log.Log;
public class CharacterEncodingFilter implements Filter {
	private static final Log log = Log.getInstance(CharacterEncodingFilter.class);
	private final static boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod(
			HttpServletResponse.class, "setCharacterEncoding", new Class[] {String.class});
	protected FilterConfig filterConfig = null;
	protected String encoding = "";
	protected boolean forceEncoding = false;

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		if (this.encoding != null && (this.forceEncoding || servletRequest.getCharacterEncoding() == null)) {
			servletRequest.setCharacterEncoding(this.encoding);
			if (this.forceEncoding && responseSetCharacterEncodingAvailable) {
				servletResponse.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
		filterConfig = null;
		encoding = null;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		log.debug("Use default encoding :"+this.encoding);
		if(filterConfig.getInitParameter("forceEncoding").equals("true")){
			this.forceEncoding = true;
		}else{
			this.forceEncoding = false;
		}
		log.debug("forceEncoding : "+this.forceEncoding);
	}
}
